<?php

namespace app\modules\Order\controllers;

use Yii;
use app\modules\Order\models\Order;
use app\modules\Order\models\OrderSearch;
use app\modules\Order\models\OrderRoom;
use app\modules\Order\models\OrderFlight;
use app\modules\Order\models\OrderGroup;
use app\modules\Order\models\OrderVisit;

use app\modules\Product\models\Product;
use app\modules\Product\models\ProductSearch;
use app\modules\Product\models\ProductRoom;
use app\modules\Product\models\ProductRoomPrice;
use app\modules\Product\models\ProductFlight;
use app\modules\Product\models\ProductGroup;
use app\modules\Product\models\ProductVisit;
use app\modules\Order\models\OrderAssign;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\web\ForbiddenHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use yii\data\Pagination;

/**
 * OrderController implements the CRUD actions for Order model.
 */
class OrderController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
		return [
			'verbs' => [
				'class' => VerbFilter::className(),
				'actions' => [
					'delete' => ['post'],
				],
			],
			'access' => [
				'class' => AccessControl::className(),
				'rules' => [
					[
						'allow' => true,
						//'actions' => ['list', 'index','create','view','update','delete'],
						'roles' => ['@'],
					],
				],
			],
		];
	}

	/***/
    public function actionList() {//{{{
		if(!Yii::$app->user->can('order_index')){
			echo "没有权限";
			return false;
		}
        $searchModel = new ProductSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('list', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }//}}}

	/** 订单分团  todo */
	public function actionAssign($product_id){//{{{
		if(!Yii::$app->user->can("order_assign")){
			echo "没有权限";
			return false;			
		}
		$product = Product::findOne($product_id);
		$assign = OrderAssign::find()->where(['product_id'=>$product_id, 'status'=>1])->all();

        return $this->render('assign', ['product' => $product, 'assign'=>$assign]);
	}//}}}

	/** 订单分团  保存 */
	public function actionAssignSave(){//{{{
		$param = Yii::$app->request->get();

		//获取现有分团的最大值
		$i = OrderAssign::find()->where(['product_id'=>$param['OrderAssign']['product_id']])->count();
		
		$orderAssign = new OrderAssign();
		$orderAssign->product_id = $param['OrderAssign']['product_id'];
		$orderAssign->name  = sprintf("团队 %d", $i+1);
		$orderAssign->save();
		
		return $this->redirect(sprintf("/order/order/assign?product_id=%d", $param['OrderAssign']['product_id']) );
	}//}}}

	/**	分团 分配人员  */
	public function actionAssignUser($product_id, $assign_id){//{{{
		//$a = [1,2,3];
		//$b = [1,2,3,4,5];
		//$c = array_diff($a, $b);
		//var_dump($c);exit;

		$this->layout = "//empty";

		$product = Product::findOne($product_id);
		$assign = OrderAssign::findOne($assign_id);

		// 获取所有未分配的订单

		$data  = [];  // 已分配给该团期的订单
		$total = 0;  // 已分配给该团期的订单总人数
		$data2 = [];  // 未分配的订单 

		$param = Yii::$app->request->get();	// 

		foreach($product->allOrder as $order){ // product->allOrder
//            print_r($order);die;

            if(empty($order->assign_id)){ // 为分团
				
				if(isset($param['userName']) && !empty($param['userName'])){	// 条件一
					if($param['userName'] != $order->username){
						continue;	
					}
				}

				if(isset($param['priceType']) && !empty($param['priceType'])){	// 条件二

					if($order->priceAll){
						$types = yii\helpers\ArrayHelper::map($order->priceAll, 'type', 'type'); // 当前订单已选择的附加费类型 
						$arr = $param['priceType'];
						if(array_diff($arr, $types) ){
							
							continue;
						}
					}else{ // 未选过附加项的定单
						continue;
					}

				}

				if(isset($param['status']) && !empty($param['status'])){	// 条件三
					if($param['status'] != $order->status){
						continue;	
					}
				}

				$data2[$order->id] = $order;
			}elseif($order->assign_id == $assign_id) { // 已份团

				$data[$order->id] = $order;
				$total += $order->customerCount;
			}
		}

        return $this->render('assign-user', ['order' => $product->allOrder, 'data'=>$data, 'data2'=>$data2, 'total'=>$total, 'assign'=>$assign, 'product'=>$product]);
	}//}}}

	public function actionAssignUserSave(){//{{{
		$assign_id = Yii::$app->request->get("assign_id");
		$order_id  = Yii::$app->request->get("order_id");
		$checked   = Yii::$app->request->get("checked");

		$order = Order::findOne($order_id);

		if($checked == 'true'){ // 添加
			$order->assign_id = $assign_id;
		}else{
			$order->assign_id = NULL;
		}

		if($order->save()){
			echo true;
		}else{
			echo false;
		}
	}//}}}

	// 清空团队下的所用用户
	public function actionAssignEmpty(){//{{{
		$assign_id = Yii::$app->request->get("assign_id");
		$product_id = Yii::$app->request->get("product_id");
		
		$ret = Order::updateAll(['assign_id'=>NULL], sprintf('assign_id = %d', $assign_id));

		return $this->redirect(sprintf("/order/order/assign?product_id=%d", $product_id));
	}//}}}

	// 删除该团队
	public function actionAssignRemove(){//{{{
		$assign_id = Yii::$app->request->get("assign_id");
		$product_id = Yii::$app->request->get("product_id");

		$ret = Order::updateAll(['assign_id'=>NULL], sprintf('assign_id = %d', $assign_id));
		$model = OrderAssign::findOne($assign_id);
		$model->status = 2;
		$model->save();

		return $this->redirect(sprintf("/order/order/assign?product_id=%d", $product_id));
	}//}}}

	// 修改团队名称
	public function actionAssignName(){//{{{
		$params = Yii::$app->request->get();
		$model = OrderAssign::findOne($params['id']);
		$model->name = $params['OrderAssign']['name'];
		$ret = $model->save();
		echo $ret;
	}//}}}

	// 订单对应的库存详细信息
	public function actionStock($product_id){//{{{
		$this->layout = false;

		$model = Product::findOne($product_id);
        return $this->render('stock', ['model' => $model]);
	}//}}}

	// 获取航期下指定房型的库存剩余数量
	public function actionProductRoomStock($product_id, $room_id){//{{{
		
		$model = Product::findOne($product_id);
		//$product_room = ProductRoom::findOne($room_id);

		$obj = $model->getSurplusRoom($room_id);

		print_r($obj);
	}//}}}

    /**
     * Lists all Order models.
     * @return mixed
     */
    public function actionIndex($product_id, $show=1){ //{{{
        if(empty($product_id)){
           throw new NotFoundHttpException('Request parameter incomplete product_id not exist.');
        }
        $searchModel = new OrderSearch();
        $dataProvider = $searchModel->search($product_id, Yii::$app->request->queryParams, $show);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'product_id' => $product_id,
            'show' => $show,
        ]);
    }//}}}

	/*  查看自己的所有订单 */
    public function actionMyIndex($show=1){ //{{{
        $searchModel = new OrderSearch();

        $data = Yii::$app->request->queryParams;
        
        // if(isset($data['OrderSearch']['product_id'])){
        // 	$product_id = $data['OrderSearch']['product_id'];
        // }else{
        // 	$product_id = NULL;
        // }

        //$dataProvider = $searchModel->search($product_id, Yii::$app->request->queryParams, $show);
        $dataProvider = $searchModel->my_search(Yii::$app->request->queryParams, $show);
        return $this->render('my-index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'show' => $show,
        ]);
    } //}}}

    /**
     * Displays a single Order model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id){ //{{{
		$model = $this->findModel($id);

		if($model->status == 4){
			
        	return $this->render('disable', ['model' => $model]);
		}else{
		
        	return $this->render('view', ['model' => $model]);
		}
    } //}}}

    /**
     * Creates a new Order model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate($product_id){//{{{

        if(empty($product_id)){
           return false;
        }
        $product = Product::findOne($product_id);
        $model = new Order();
            
        $params = Yii::$app->request->post();
	
        if(isset($params['room']) && $model->load($params) && $model->save()) {

            // 保存完成 设置船舱
			if($product->stock == 1){ // 国内航线 标准库存格式
				
				Yii::$app->orderblock->create($params, $model);
			}elseif($product->stock == 2){ // 海外航线  自定义库存格式
				
				Yii::$app->orderblock->create2($params, $model);
			}
            
			//	$ret = Yii::$app->orderblock->commiss($model);

            return $this->redirect(['view', 'id' => $model->id]);
        }else{
            $model->product_id = $product_id;
            $model->status = 1;
            $model->source = 1;
            $model->is_merge  = 1;

            return $this->render('create', ['model' => $model, 'product'=>$product]);
        }
    }//}}}
	
	/** 添加舱房 ***/
    public function actionEditRoom($id){//{{{
        if(empty($id)){
           return false;
        }
		
        $model = $this->findModel($id);
		$product = Product::findOne($model->product_id);
            
        $params = Yii::$app->request->post();
	
        if(isset($params['room']) ){

            // 保存完成 设置船舱
			if($product->stock == 1){ // 国内航线 标准库存格式
				
				Yii::$app->orderblock->create($params, $model, 2);
			}elseif($product->stock == 2){ // 海外航线  自定义库存格式
				
				Yii::$app->orderblock->create2($params, $model, 2);
			}

			// 变更订单状态
			Yii::$app->orderblock->order_status($model);

			// 佣金计算 todo 
			//Yii::$app->orderblock->commiss($model);
           	
            return $this->redirect(['view', 'id' => $model->id]);
        }
    }//}}}

    /**
     * 保存订单机票信息
    */
    private function itemFlight($data, $order_id){//{{{

        $flight = isset($data['flight']) ? $data['flight'] : NULL;

        if($flight && $flight['num']>0){
            $flightModel  = ProductFlight::findOne($flight['id']);

            if($flight['num'] > $flightModel->num){

                throw new NotFoundHttpException('订单机票数量不够, 请重新添加.');
            }

            $db = Yii::$app->db;

            $transaction = $db->beginTransaction();
            
            try{

                for($i=0; $i<$flight['num']; $i++){
                    $model = new OrderFlight();             
                    $model->flight_id  = $flight['id'];
                    $model->order_id = $order_id;

                    if(! $model->save()){

                        throw new NotFoundHttpException('订单机票保存失败, 请重新添加.');
                    }
                }
                
                $flightModel->num = $flightModel->num - $flight['num'];
                
                if(! $flightModel->save()){
                    
                    throw new NotFoundHttpException('订单机票保存失败.');
                }

                $transaction->commit();

            }catch(\Exception $e) {

                $transaction->rollBack();
                throw $e;
            }
        }

    }//}}}


    /**
     * 保存订单酒店信息
    */
    private function itemGroup($data, $order_id){//{{{

        $group  = isset($data['group']) ? $data['group'] : NULL;

        if($group && $group['num']>0){

            $groupModel  = ProductGroup::findOne($group['id']);

            if($group['num'] > $groupModel->num){

                throw new NotFoundHttpException('订单酒店数量不够, 请重新添加.');
            }

            $db = Yii::$app->db;

            $transaction = $db->beginTransaction();
            
            try{
                for($i=0; $i<$group['num']; $i++){
                    $model = new OrderGroup();             
                    $model->group_id  = $group['id'];
                    $model->order_id = $order_id;

                    if(! $model->save()){

                        throw new NotFoundHttpException('订单酒店保存失败, 请重新添加.');
                    }
                }
                
                $groupModel->num = $groupModel->num - $group['num'];
                
                if(! $groupModel->save()){
                    
                    throw new NotFoundHttpException('订单酒店库存减少失败.');
                }

                $transaction->commit();

            }catch(\Exception $e) {

                $transaction->rollBack();
                throw $e;
            }
        }

    }//}}}


    /**
     * 保存订单岸上游信息
    */
    private function itemVisit($data, $order_id){//{{{

        $visit = isset($data['visit']) ? $data['visit'] : NULL;

        if($visit && $visit['num']>0){

            $visitModel  = ProductVisit::findOne($visit['id']);

            if($visit['num'] > $visitModel->num){

                throw new NotFoundHttpException('订单岸上游产品数量不够, 请重新添加.');
            }

            $db = Yii::$app->db;

            $transaction = $db->beginTransaction();
            
            try{
                for($i=0; $i<$visit['num']; $i++){
                    $model = new OrderVisit();             
                    $model->visit_id  = $visit['id'];
                    $model->order_id = $order_id;

                    if(! $model->save()){

                        throw new NotFoundHttpException('订单岸上游产品保存失败, 请重新添加.');
                    }
                }
                
                $visitModel->num = $visitModel->num - $visit['num'];
                
                if(! $visitModel->save()){
                    
                    throw new NotFoundHttpException('订单岸上游产品库存减少失败.');
                }

                $transaction->commit();

            }catch(\Exception $e) {

                $transaction->rollBack();
                throw $e;
            }
        }

    }//}}}

    //优惠金额
    public function actionEditPrice(){//{{{
        $data = yii::$app->request->get(); 
        if(isset($data['Order']['id']) && isset($data['Order']['sale_price'])){
            $model = $this->findModel($data['Order']['id']);

            $sale_price = $data['Order']['sale_price'];

            $model->sale_price = $sale_price;
            
			// 状态变更为待审核
			$model->check = 2;

            if($model->save()){
                $res = ['price'=>$model->price,'sale_price'=>$model->sale_price];
                print_r(json_encode($res)); 
            }
        }else{
            $res = '';
            print_r(json_encode($res));
        }
    }//}}}

	// 状态变更
	public function actionEditStatus(){//{{{
        $data = yii::$app->request->get(); 

        if(isset($data['Order']['id']) && isset($data['Order']['status'])){
            $model = $this->findModel($data['Order']['id']);
			
			$ex = true;
			if($data['Order']['status'] == 4){ // 确认提交 验证数据是否完整

				$customers = $model->customer; // 获取订单对应的人员
				if($customers){
					foreach($customers as $customer){
						if($customer->first_name && $customer->last_name && $customer->birthday && $customer->country &&  $customer->passport && $customer->passport_add && $customer->passport_grant && $customer->passport_date && $customer->passport_img && $customer->native){
						}else{
							$ex = false;
						}
					}
				}

				if($model->check == 2){ // 优惠尚未审核
					$ex = false;
				}

				$refunds = $model->refund; // 获取订单取消的舱房
				if($refunds){
					foreach($refunds as $refund){
						if($refund->status == 1){ // 舱房退款尚未审批
							$ex = false;
						}
					}
				}

			}
			if($ex == false){
				
				print_r(json_encode(['output'=>Yii::$app->params['order_status'][$model->status], 'message'=>"无法提交, 用户资料填写不完整,优惠或舱房退款未审核" ]));
				return ;
			}

			$model->status = $data['Order']['status'];
			$model->save();
		}
		print_r(json_encode(['output'=>Yii::$app->params['order_status'][$model->status], 'message'=>"" ]));

		if($model->status == 4){

			$this->redirect('/order/order/view?id='. $model->id);	
		}
	}//}}}

	// 已提交 退回至 已付款状态
	public function actionBackStatus(){//{{{

	    $data = yii::$app->request->get();

		$ret = false;

        if( isset($data['id']) ){
			$model = $this->findModel($data['id']);		 
			if($model->status == 4){ // 确认提交
				$model->status = 3;  // 变更为已付款	
				$ret = $model->save();
			}
		}
		if($ret){
			
            return $this->redirect(['view', 'id' => $model->id]);
		}
	}//}}}}
	
	// 订单金额明细
    public function actionPriceDetail($id){//{{{
		$this->layout = false;
        if($id){
            $model = $this->findModel($id);

        	return $this->render('price-detail', ['model' => $model]);
        }
    }//}}}

	// 审核
	public function actionCheck($id){//{{{
        //$data = yii::$app->request->get(); 

        if(isset($id) ){
            $model = $this->findModel($id);
			$model->check = 1;
			$ret = $model->save();

			//echo $ret;
        	return $this->render('view', [
        	    'model' => $model,
        	]);
		}
	}//}}}

	// 保存异步信息
	public function actionEditAjax(){//{{{
        $data = yii::$app->request->get(); 

        if(isset($data['Order']['id'])){
            $model = $this->findModel($data['Order']['id']);
			$model->load($data);
			$ret = $model->save();
		}

		echo $ret;
	}//}}}

	// 佣金修改
	public function actionCommissAjax(){//{{{
        $data = yii::$app->request->get(); 
		
		$r = true;
        if(isset($data['Order']['id'])){
            $model = $this->findModel($data['Order']['id']);
			$model->load($data);
			$ret = $model->save();
			//  佣金计算
			$r = Yii::$app->orderblock->commiss($model);
		}
		if($r !== true){
			print_r(json_encode(['output'=>$r, 'message'=>"佣金金额无效, 佣金最大上线  ". $r ]));
		}else{
			print_r($r);
		}
	}//}}}

	// 佣金列表
	public function actionCommissList($product_id){//{{{
        if(empty($product_id)){
           throw new NotFoundHttpException('Request parameter incomplete product_id not exist.');
        }
        $searchModel = new OrderSearch();
        $dataProvider = $searchModel->search($product_id, Yii::$app->request->queryParams);

        return $this->render('commiss-list', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'product_id' => $product_id,
        ]);
	
	}//}}}

	// 关联订单
	public function actionRelationOrder($id){//{{{
		//$this->layout = "//empty";
		// 判断订单是否是主订单 [未绑定到其它订单]
		$model = $this->findModel($id);
		if($model->status >= 10){
			echo "<h3>已取消订单不能做关联订单操作</h3>";
			return false;
		}

		/**
		 * 获取符合条件的订单
		 * 1.	状态为正常的订单 
		 * 2.	不包含本身
		 * 3.	未分配过到其它订单做关联子订单
		 * 4.	未被分配子关联订单
		 */
		if($model->id == $model->relation){ // 主订单或未分配
			$data = Order::find();
			$data->where(['product_id'=>$model->product_id]);
			$data->andWhere(['!=', 'id', $model->id]);
			$data->andWhere(['status'=> [1,3,4] ]);
			$data->andWhere(['member_id'=>yii::$app->user->identity->id ]);
			$data->groupBy(['relation'])->having(new \yii\db\Expression('count(relation)=1 and id=relation'));
			//->andWhere(new \yii\db\Expression('id=relation'))  //->all();

			$params = Yii::$app->request->get();
			if(isset($params['code']) && !empty($params['code'])){
				$data->andWhere(['code'=>$params['code']]);	
			}
			
			if(isset($params['username']) && !empty($params['username'])){
				$data->andWhere(['username'=>$params['username']]);	
			}

			$pages = new Pagination(['totalCount' =>$data->count(), 'pageSize' => 10]);

			$ret = $data->offset($pages->offset)->limit($pages->limit)->all();

			// 获取已关联的订单
			$already =  Order::find()->where(['product_id'=>$model->product_id, 'relation'=>$id])
							 	 ->andWhere(['!=', 'id', $model->id])
								 ->all();

        	return $this->render('relation-order', ['model' => $model, 'data'=>$ret, 'already'=>$already, 'pages'=>$pages, 'params'=>$params]);

		}else{ // 被分配的子订单

			// 获取已关联的主订单
			$already =  Order::find()->where(['product_id'=>$model->product_id, 'id'=>$model->relation])->one();

        	return $this->render('relation-order2', ['model' => $model, 'already'=>$already] );
		}

	}//}}}

	// 保存关联订单
	public function actionRelationSave(){//{{{

		$data = Yii::$app->request->get();

		$model = $this->findModel($data['child_id']);

        if($data['checked'] == 'true'){

			$model->relation = $data['parent_id'];
		}else{
			
			$model->relation = $model->id;
		}

		$ret = $model->save();
		print_r($ret);	
	}//}}}

    /**
     * Updates an existing Order model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id){//{{{
		//$this->layout = false;
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }//}}}

    /**
     * Deletes an existing Order model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

	// 取消订单
    public function actionUnrecovery($id){//{{{

        $model = $this->findModel($id);

		// 判断是否已被分团占用
		if(!empty($model->assign_id)){
			echo "订单已分团， 不能取消, 请先在团队中移除该订单"; 	
			return false;
		}

		// 判断是否是关联订单
		if($model->isRelation > 1){
			echo "关联订单, 请先取消关联后操作";	
			return false;
		}

		// 判断是否拼房
		if($model->merge_id){
			echo "该订单已拼房, 请先取消拼住的舱房";	
			return false;
		}

		// 更改订单状态 
			/*
                1 => '占位',
                2 => '定金',
                3 => '已付款',
                4 => '确认提交',
                10 => '占位-取消',
                11 => '付款-取消',
                12 => '提交-取消',   
			*/
		if($model->status == 1){	// 占位取消
			
			$model->status = 10;
		}elseif($model->status == 2){	// 定金取消

			$model->status = 13;
		}elseif($model->status == 3){	// 付款取消

			$model->status = 11;
		}elseif($model->status == 4){	// 提交取消
		
			$model->status = 12;
		}

		$model->save();

		// 更改订单所属舱房的状态
		OrderRoom::updateAll(['status'=>2], sprintf('order_id = %d', $id) );

        return $this->redirect(['view', 'id'=>$model->id]);
    }//}}}

	// 恢复已取消的订单
    public function actionRecovery($id){//{{{
        $model = $this->findModel($id); 	// ORDER MODEL

		if($model->status != 10){ // 占位取消的订单才容许恢复
			
			return false;
		}
		
		// 判断库存数量是否足够
		$ret = Yii::$app->orderblock->isStock($model);
		// 只容许占位取消订单恢复
		if($ret){
			
			// 更改订单状态 判断当前订单属于何种状态 todo 
			$model->status = 1;
			$model->save();

			// 更改订单所属舱房的状态
			OrderRoom::updateAll(['status'=>1], sprintf('order_id = %d', $id));
        	return $this->redirect(['index', 'product_id'=>$model->product_id]);
		}else{
			echo "库存余额不足";
		}
		//return $this->goBack();
    }//}}}


    //打包护照资料
    public function actionPack($product_id)
    {
        //获取航期信息
        $model = Product::findOne($product_id);
        $orders = Order::find()->where(['product_id'=>$product_id])->andwhere(['<=','status',4])->all();
        if(empty($orders)){
           header('Content-type:text/html;charset=utf-8');
           echo "该船期下没有订单!";exit();
        }
        //获取该航期的分团
        $assign = OrderAssign::find()->where(['product_id'=>$product_id,'status'=>1])->all();
        if(empty($assign)){
           header('Content-type:text/html;charset=utf-8');
           echo "没有分团!";exit();
        }
        $zip = new \ZipArchive;//打包
        //打包文件名
        $filename = sprintf("%s_%s的护照资料.zip",$model->name,date("Y年m月d日",strtotime($model->go_time)));
        $filename = str_replace("\"","",$filename); //删除双引号
        $filename = str_replace("'","",$filename);  //删除单引号
        $filename = str_replace("\\","",$filename); //删除斜杠
        $filename = preg_replace("/\s/","",$filename); //去除空格
        //文件名
        $file = $filename; 
        $filename = sprintf("%s/web/uploads/zip/%s",Yii::$app->basePath,$filename);
        $filename = iconv("UTF-8","GBK//IGNORE",$filename); //中文乱码
        $res = $zip->open($filename, \ZipArchive::OVERWRITE);//如果打包文件有就覆盖
        if($res === TRUE) {
            foreach($assign as $v){
                //获取团号 转中文
                $assign_dir = iconv("UTF-8","GBK//IGNORE",$v->name);
                //$assign_dir = preg_replace("/\s/","",$assign_dir); //去除空格
                //建文件
                $zip->addEmptyDir($assign_dir);
                foreach ($v->orders as $o) {
                	//先找房间 再找人
                	foreach($o->room as $room){

                		//if($room->stock == 1){ //计入库存
                			foreach($room->orderRoomCustomer as $c){
                			   //新的文件名
		                        if(!empty($c->orderCustomer->passport_img)){
		                            $name = $c->orderCustomer->first_name.$c->orderCustomer->last_name;
		                            $name = iconv("UTF-8", "GBK//IGNORE", $name);
		                            $newName = $name.'_'.$c->orderCustomer->phone.'.'.$this->getExt($c->orderCustomer->passport_img);
		                            $zip->addFile($c->orderCustomer->passport_img,sprintf("%s/%s",$assign_dir,$newName)); 
		                        }         
	                		}
     	  
                	}

                  
                }
            }
            $zip->close();
        }   

        header ( "Cache-Control: max-age=0" );
        header ( "Content-Description: File Transfer" );
        header ( 'Content-disposition: attachment; filename=' .$file); // 文件名
        header ( "Content-Type: application/zip" ); // zip格式的
        header ( "Content-Transfer-Encoding: binary" ); // 告诉浏览器，这是二进制文件
        header ( 'Content-Length: ' . filesize ( $filename ) ); // 告诉浏览器，文件大小
        @readfile ( $filename );//输出文件;

    }
    //打包户口本或身份证资料
    public function actionCardPack($product_id)
    {
        //获取航期信息
        $model = Product::findOne($product_id);
        $orders = Order::find()->where(['product_id'=>$product_id])->andwhere(['<=','status',4])->all();
        if(empty($orders)){
           header('Content-type:text/html;charset=utf-8');
           echo "该船期下没有订单!";exit();
        }
        //获取该航期的分团
        $assign = OrderAssign::find()->where(['product_id'=>$product_id,'status'=>1])->all();
        if(empty($assign)){
           header('Content-type:text/html;charset=utf-8');
           echo "没有分团!";exit();
        }
        $zip = new \ZipArchive;//打包
        //打包文件名
        $filename = sprintf("%s_%s的身份证或户口本资料.zip",$model->name,date("Y年m月d日",strtotime($model->go_time)));
        $filename = str_replace("\"","",$filename); //删除双引号
        $filename = str_replace("'","",$filename);  //删除单引号
        $filename = str_replace("\\","",$filename); //删除斜杠
        $filename = preg_replace("/\s/","",$filename); //去除空格
        //文件名
        $file = $filename; 
        $filename = sprintf("%s/web/uploads/zip/%s",Yii::$app->basePath,$filename);
        $filename = iconv("utf-8","gbk//ignore",$filename); //中文乱码
        $res = $zip->open($filename, \ZipArchive::OVERWRITE);//如果打包文件有就覆盖
        if($res === TRUE) {
            foreach($assign as $v){
                //获取团号 转中文
                $assign_dir = iconv("utf-8","gbk//ignore",$v->name);
                //$assign_dir = preg_replace("/\s/","",$assign_dir); //去除空格
                //建文件
                $zip->addEmptyDir($assign_dir);
                foreach ($v->orders as $o) {
                	//先找房间 再找人
                	foreach($o->room as $room){

                		//if($room->stock == 1){ //计入库存
                			foreach($room->orderRoomCustomer as $c){
                			   //新的文件名
		                        if(!empty($c->orderCustomer->card_img)){
		                        	$name = $c->orderCustomer->first_name.$c->orderCustomer->last_name;
		                            $name = iconv("UTF-8", "GBK//IGNORE", $name);
		                            $newName = $name.'_'.$c->orderCustomer->phone.'.'.$this->getExt($c->orderCustomer->card_img);
		                            $zip->addFile($c->orderCustomer->card_img,sprintf("%s/%s",$assign_dir,$newName)); 
		                        }         
	                		}
     
                	}
                }
            }
            $zip->close();
        }   

        header ( "Cache-Control: max-age=0" );
        header ( "Content-Description: File Transfer" );
        header ( 'Content-disposition: attachment; filename=' .$file); // 文件名
        header ( "Content-Type: application/zip" ); // zip格式的
        header ( "Content-Transfer-Encoding: binary" ); // 告诉浏览器，这是二进制文件
        header ( 'Content-Length: ' . filesize ( $filename ) ); // 告诉浏览器，文件大小
        @readfile ( $filename );//输出文件;

    }
    //获取文件后缀名
    private function getExt($url) 
    { 
        $path = parse_url($url); 
        $str = explode('.',$path['path']); 
        return $str[1]; 
    } 

    /**
     * @param integer $id
     * @return Order the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id){//{{{

        if (($model = Order::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }//}}}


	/**
	 * 优惠审批
	 */
	public function actionSalePrice(){//{{{

		if(!Yii::$app->user->can("sale_check")){
			return false;
		}

        $params = Yii::$app->request->get();
		//print_r($params);exit;
		$model = new Order();
		$model->load($params);

		// 获取所有未过期的船期
		$product = Product::find()->select("id, go_time")->where(['>', 'go_time', date('Y-m-d', strtotime('-3 month'))])->andWhere(['status'=>1]);

		if(isset($params['Order']['product']['go_time']) && !empty($params['Order']['product']['go_time']) ){
			$product->andWhere(['go_time'=>$params['Order']['product']['go_time']]);

			//$model->product['go_time'] = $params['Order']['product']['go_time'];
		}

		if(isset($params['Order']['product']['name'])  && !empty($params['Order']['product']['name']) ){
			$product->andWhere(['like', 'name', $params['Order']['product']['name']]);
		}

		$data = $product->all();

		$ids = \yii\helpers\ArrayHelper::map($data, 'id', 'id');

		// 获取该船期下的所有订单  有附加费 且 未审核
		$order = Order::find()->where(['product_id'=>$ids, 'check'=>2, 'status'=>[1,2,3,4]] )
							  ->andWhere(['>=', 'sale_price', 0]);

		if(isset($params['Order']['username'])  && !empty($params['Order']['username']) ){
			$order->andWhere(['username' => $params['Order']['username'] ]);
		}

		if(isset($params['Order']['code'])  && !empty($params['Order']['code']) ){
			$order->andWhere(['code' => $params['Order']['code'] ]);
		}

		if(isset($params['Order']['status'])  && !empty($params['Order']['status']) ){
			$order->andWhere(['status' => $params['Order']['status'] ]);
		}

		$all = $order->all();


        return $this->render('sale-price', ['all'=>$all, 'model'=> $model, 'params'=>$params ] );
	}//}}}
	
	// 优惠审批
	public function actionSalePriceSave($id){//{{{

		$model = $this->findModel($id);

		$ret = false;

		if($model){

			// 计算优惠金额	 todo
            $price = $model->total_sale - $model->sale_price - $model->commiss;
            //$price = $model->total_sale - $model->sale_price;	// $model->commiss_price;

			// 计算附加费金额
			if($model->priceSum){
				$price = $price+$model->priceSum;
			}

            $price = ($price <=0) ? 0 : $price;
            $model->price = $price;

			$model->check = 1;
			$ret = $model->save();

			// 变更订单状态
			Yii::$app->orderblock->order_status($model);
		}

		echo $ret;
	}//}}}

	// 订单操作记录
	public function actionLog($id, $type =1){
		$this->layout = "//empty";		
		$data = Yii::$app->logs->message($id, $type);
        return $this->render('log', ['data' => $data]);
	}
	
	// 二级联动获取指定团期下的订单
	public function actionDeplist(){//{{{
		Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        $params = $_POST['depdrop_parents'];
        $product_id = $params[0]; 

        $model = Order::find()->select('id, code ,username');
		$model->andWhere(['product_id'=>$product_id ,'status'=>[3,4]]);

		if(!Yii::$app->user->can('is_admin')){
			$model->andWhere(['user_id' => Yii::$app->user->identity->id]);
		}

		$data = $model->all();
		
		$res = [];
		if($data){
			foreach($data as $key=>$val){
				$res[$key]['id'] = $val->id;
				$res[$key]['name'] = sprintf("%s / %s", $val->code, $val->username);
			}
		}
        
        return ['output'=>$res, 'selected'=>''];        
    }//}}}


	// 获取订单其它待合房订单
	public function actionMergeList($id, $room_id){//{{{
	
		$this->layout = "//empty";		
		$model = $this->findModel($id);

		if($model->merge_id){ // 已拼房
			$data = Order::find()->where(['id'=>$model->merge_id])->andWhere(['is_merge'=>2])->all();
		}else{
			$data = Order::find()->andWhere(['product_id'=>$model->product_id])->andWhere(['is_merge'=>2])->andWhere(['status'=>[1,3,4]])->andWhere(['merge_id'=>NULL])->andWhere(['!=', 'id', $model->id])->all();
		}

        return $this->render('merge-list', ['data' => $data , 'model'=>$model, 'room_id'=>$room_id]);
	}//}}}


	// 订单拼房保存
	public function actionMergeSave(){//{{{
		$order_id = Yii::$app->request->get("order_id");
		$merge_id = Yii::$app->request->get("merge_id");
		$room_id  = Yii::$app->request->get("room_id");
		$room 	  = Yii::$app->request->get("room");


		$checked   = Yii::$app->request->get("checked");

		$order  = Order::findOne($order_id);
		$order2 = Order::findOne($merge_id);

		$order_room = OrderRoom::findOne($room);
		$order_room2 = OrderRoom::findOne($room_id);

		//航线
		$product = Product::findOne($order->product_id);
		if($product->stock == 1){
			$product_room  = ProductRoom::findOne($order_room->room_id);
			$product_room2  = ProductRoom::findOne($order_room2->room_id);
			$pr_price = $product_room->price;
			$pr2_price = $product_room2->price;
			$pr_inside_price = $product_room->inside_price;
			$pr2_inside_price = $product_room2->inside_price;
		}else if($product->stock == 2 ){
			$room_json = json_decode($product->rooms, true);
			$product_room   = $room_json[$order_room->room_id];
			$product_room2  = $room_json[$order_room2->room_id];
			$pr_price = $product_room['price'];
			$pr2_price = $product_room2['price'];
			$pr_inside_price = $product_room['inside_price'];
			$pr2_inside_price = $product_room2['inside_price'];
		}
		

		if($checked == 'true'){ // 添加
			// 验证本次绑定是否合法
			if($order->merge_id || $order2->merge_id){
				//echo "该订单已做过拼房, 每个订单只能做一次拼房";	
				return 'already_order';
			}
			if($order_room->merge_id || $order_room->merge_id){
				//echo "该房间已做过拼房, 每个房间只能做一次拼房";	
				return 'already_room';		
			}

			$order->merge_id = $merge_id;
			$order2->merge_id = $order_id;

			$order_room->merge_id = $room_id; 	// 对应舱房编号

			$order_room2->stock = 2; 	// 标识为不计入库存
			$order_room2->merge_id = $room; 	// 对应舱房编号
			// 把待拼房的房间置为不计入库存
			if($order_room->num == 2 && $order_room2->num == 2){ //拼房2人间 自动减少一人金额
				$order_room->num = 1;
				$order_room2->num = 1;
				if($order->source == 1){
					$order->total_sale = $order->total_sale - $pr_price;
					$order->price = $order->price - $pr_price;
					$order2->total_sale = $order2->total_sale - $pr2_price;
					$order2->price = $order2->price - $pr2_price;

					$order_room->price = $order_room->price - $pr_price;
					$order_room2->price = $order_room2->price - $pr2_price;

				}else if($order->source == 2){
					$order->total_sale = $order->total_sale - $pr_inside_price;
					$order->price = $order->price - $pr_inside_price;
					$order2->total_sale = $order2->total_sale - $pr2_inside_price;
					$order2->price = $order2->price - $pr2_inside_price;

					$order_room->price = $order_room->price - $pr_inside_price;
					$order_room2->price = $order_room2->price - $pr2_inside_price;
				}

			}

		}else{
			$order->merge_id = NULL;
			$order2->merge_id = NULL;
			$order_room->merge_id = NULL; 	// 对应舱房编号 
			$order_room2->merge_id = NULL; 	// 对应舱房编号

			if($order_room->stock == 2){
				$order_num = $product->getSurplusRoom($order_room->room_id); //剩余舱房数
				if($order_num <= 0){
					return 'room_num';
				}
			}
			if($order_room2->stock == 2){
				$order_num2 = $product->getSurplusRoom($order_room2->room_id); //剩余舱房数
				if($order_num2 <= 0){
					return 'room_num';
				}
			}
			
			$order_room2->stock = 1; 		// 标识为计入库存
			$order_room->stock = 1; 		// 标识为计入库存

			if($order_room->num == 1 && $order_room2->num == 1){ //拼房2人间 
				$order_room->num = 2;
				$order_room2->num = 2;
				if($order->source == 1){
					$order->total_sale = $order->total_sale + $pr_price;
					$order->price = $order->price + $pr_price;
					$order2->total_sale = $order2->total_sale + $pr2_price;
					$order2->price = $order2->price + $pr2_price;

					$order_room->price = $order_room->price + $pr_price;
					$order_room2->price = $order_room2->price + $pr2_price;

				}else if($order->source == 2){
					$order->total_sale = $order->total_sale + $pr_inside_price;
					$order->price = $order->price + $pr_inside_price;
					$order2->total_sale = $order2->total_sale + $pr2_inside_price;
					$order2->price = $order2->price + $pr2_inside_price;

					$order_room->price = $order_room->price + $pr_inside_price;
					$order_room2->price = $order_room2->price + $pr2_inside_price;
				}

			}
		}

		if($order->save() && $order2->save() && $order_room->save() && $order_room2->save()){
			echo true;
		}else{
			echo false;
		}

		
	}//}}}

	//确认单
	public function actionConfirms($product_id,$show=1){
		if(empty($product_id)){
			return false;
		}

		$searchModel = new OrderSearch();
        $dataProvider = $searchModel->search($product_id, Yii::$app->request->queryParams, $show);

        return $this->render('confirms', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'product_id' => $product_id,
            'show' => $show,
        ]);
	}

	

}
